import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' show SelectableText;
import 'package:flutter/services.dart';
import 'package:macos_ui/macos_ui.dart';
import '../models/mcp_tool.dart';

/// 结果展示组件
class ResultViewer extends StatelessWidget {
  final McpToolResult? result;

  const ResultViewer({super.key, this.result});

  String _formatJson(dynamic data) {
    try {
      const encoder = JsonEncoder.withIndent('  ');
      return encoder.convert(data);
    } catch (e) {
      return data.toString();
    }
  }

  void _copyToClipboard(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    showMacosAlertDialog(
      context: context,
      builder: (context) => MacosAlertDialog(
        appIcon: const Icon(CupertinoIcons.checkmark_circle),
        title: const Text('已复制'),
        message: const Text('结果已复制到剪贴板'),
        primaryButton: PushButton(
          controlSize: ControlSize.large,
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('确定'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (result == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              CupertinoIcons.doc_text,
              size: 48,
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.3),
            ),
            const SizedBox(height: 16),
            Text(
              '暂无结果',
              style: MacosTheme.of(context).typography.body.copyWith(
                color: MacosTheme.of(
                  context,
                ).typography.body.color?.withOpacity(0.5),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '测试工具以查看结果',
              style: MacosTheme.of(context).typography.caption1.copyWith(
                color: MacosTheme.of(
                  context,
                ).typography.body.color?.withOpacity(0.5),
              ),
            ),
          ],
        ),
      );
    }

    final formattedResult = _formatJson(result!.result);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Header
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: result!.success
                ? MacosColors.systemGreenColor.withOpacity(0.1)
                : MacosColors.systemRedColor.withOpacity(0.1),
            border: Border(
              bottom: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: Row(
            children: [
              Icon(
                result!.success
                    ? CupertinoIcons.checkmark_circle_fill
                    : CupertinoIcons.xmark_circle_fill,
                color: result!.success
                    ? MacosColors.systemGreenColor
                    : MacosColors.systemRedColor,
                size: 24,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      result!.success ? '成功' : '错误',
                      style: MacosTheme.of(
                        context,
                      ).typography.title3.copyWith(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      result!.toolName,
                      style: MacosTheme.of(context).typography.caption1
                          .copyWith(
                            color: MacosTheme.of(
                              context,
                            ).typography.body.color?.withOpacity(0.7),
                          ),
                    ),
                  ],
                ),
              ),
              Text(
                _formatTimestamp(result!.timestamp),
                style: MacosTheme.of(context).typography.caption1.copyWith(
                  color: MacosTheme.of(
                    context,
                  ).typography.body.color?.withOpacity(0.6),
                ),
              ),
            ],
          ),
        ),
        // Result content
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: result!.success
                ? _buildSuccessContent(context, formattedResult)
                : _buildErrorContent(context),
          ),
        ),
        // Action buttons
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            border: Border(
              top: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              PushButton(
                controlSize: ControlSize.large,
                secondary: true,
                onPressed: () => _copyToClipboard(
                  context,
                  result!.success ? formattedResult : result!.error ?? '',
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: const [
                    Icon(CupertinoIcons.doc_on_clipboard, size: 16),
                    SizedBox(width: 8),
                    Text('复制'),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildSuccessContent(BuildContext context, String formattedResult) {
    return Container(
      decoration: BoxDecoration(
        color: MacosTheme.of(context).brightness == Brightness.dark
            ? MacosColors.black.withOpacity(0.3)
            : MacosColors.white.withOpacity(0.5),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: MacosTheme.of(context).dividerColor),
      ),
      padding: const EdgeInsets.all(16),
      child: SelectableText(
        formattedResult,
        style: MacosTheme.of(
          context,
        ).typography.body.copyWith(fontFamily: 'Courier', fontSize: 13),
      ),
    );
  }

  Widget _buildErrorContent(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: MacosColors.systemRedColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: MacosColors.systemRedColor.withOpacity(0.3)),
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                CupertinoIcons.exclamationmark_triangle,
                color: MacosColors.systemRedColor,
                size: 20,
              ),
              const SizedBox(width: 8),
              Text(
                '错误详情',
                style: MacosTheme.of(context).typography.body.copyWith(
                  fontWeight: FontWeight.bold,
                  color: MacosColors.systemRedColor,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          SelectableText(
            result!.error ?? '未知错误',
            style: MacosTheme.of(
              context,
            ).typography.body.copyWith(fontFamily: 'Courier', fontSize: 13),
          ),
        ],
      ),
    );
  }

  String _formatTimestamp(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inSeconds < 60) {
      return '刚刚';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} 分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} 小时前';
    } else {
      return '${timestamp.day}/${timestamp.month}/${timestamp.year} ${timestamp.hour}:${timestamp.minute.toString().padLeft(2, '0')}';
    }
  }
}
